package com.qingrongby.shop.core;

import com.qingrongby.shop.core.config.ApplicationExceptionConfiguration;
import com.qingrongby.shop.exception.http.HttpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {

    @Autowired
    public ApplicationExceptionConfiguration applicationExceptionConfiguration;

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public UnifyResponse handException(HttpServletRequest request, Exception e) {
        String requestUrl = request.getRequestURI();
        String method = request.getMethod();
        UnifyResponse message = new UnifyResponse(9999, "系统出错了", method + " " + requestUrl);
        log.error(e.getMessage());
        return message;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public UnifyResponse handMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
        String requestsUrl = request.getRequestURI();
        String method = request.getMethod();
        List<ObjectError> objectErrors = e.getBindingResult().getAllErrors();
        String message = objectErrors.get(0).getDefaultMessage();
        log.error(e.getMessage());

        return new UnifyResponse(1001, message, method + " " + requestsUrl);
    }

    @ExceptionHandler(value = HttpException.class)
    @ResponseBody
    public ResponseEntity<UnifyResponse> handHttpException(HttpServletRequest request, HttpException e) {
        String requestUrl = request.getRequestURI();
        String method = request.getMethod();
        UnifyResponse message = new UnifyResponse(e.code, applicationExceptionConfiguration.getMessage(e.code), method + " " + requestUrl);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        ResponseEntity<UnifyResponse> responseResponseEntity =
                new ResponseEntity<>(message, httpHeaders, HttpStatus.resolve(e.getHttpCode()));
        log.error(e.getMessage());

        return responseResponseEntity;
    }


}
